package com.hghivln.erpwarehouse.system.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/**
 * 全局跨域配置
 * 解决跨域问题
 */
@Configuration
public class CrosAutoConfig {

    @Bean
    public CorsFilter crosFilter() {
        UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
        // 1.添加CORS配置信息
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        // 允许头部设置
        corsConfiguration.addAllowedHeader("*");
        // 允许跨域访问的源
        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.addAllowedMethod("*");
        // 预检间隔时间  默认缓存30min
        corsConfiguration.setMaxAge(1800L);
        // 是否发送cookie
        corsConfiguration.setAllowCredentials(true);
        // 2.添加映射路径，我们拦截一切请求
        urlBasedCorsConfigurationSource.registerCorsConfiguration("/**",corsConfiguration);
        // 3.返回新的CorsFilter
        return new CorsFilter(urlBasedCorsConfigurationSource);
    }
}
